package com.lj.system.service.impl;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.lj.common.constant.BaseConstant;
import com.lj.common.utils.security.SecurityUtil;
import com.lj.system.mapper.SysMenuMapper;
import com.lj.system.model.SysMenu;
import com.lj.system.model.vo.MetaVo;
import com.lj.system.model.vo.RouterVo;
import com.lj.system.service.ISysMenuService;
import org.apache.commons.compress.utils.Sets;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单权限表 服务实现类
 * </p>
 *
 * @author 小李飞刀
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

    @Resource
    private SysMenuMapper menuMapper;

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public Set<String> selectMenuPermsByUserId(Long userId) {
        List<String> perms = menuMapper.selectMenuPermsByUserId(userId);
        Set<String> permsSet = Sets.newHashSet();
        for (String perm : perms) {
            if (CharSequenceUtil.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 根据用户ID查询菜单
     *
     * @param userId 用户ID
     * @return 菜单树
     */
    @Override
    public List<SysMenu> selectMenuTreeByUserId(Long userId) {
        if (SecurityUtil.isAdmin(userId)) {
            return getChildPerms(menuMapper.selectMenuTreeAll(), 0);
        } else {
            return getChildPerms(menuMapper.selectMenuTreeByUserId(userId), 0);
        }
    }

    @Override
    public List<RouterVo> buildMenus(List<SysMenu> menus) {
        List<RouterVo> routers = Lists.newLinkedList();
        for (SysMenu menu : menus) {
            RouterVo router = new RouterVo();
            router.setHidden("1".equals(menu.getVisible()));
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setQuery(menu.getQuery());
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), CharSequenceUtil.equals("1", menu.getIsCache()), menu.getPath()));
            List<SysMenu> cMenus = menu.getChildren();
            if (!cMenus.isEmpty() && BaseConstant.TYPE_DIR.equals(menu.getMenuType())) {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            } else if (isMenuFrame(menu)) {
                router.setMeta(null);
                List<RouterVo> childrenList = Lists.newLinkedList();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(CharSequenceUtil.upperFirst(menu.getPath()));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), CharSequenceUtil.equals("1", menu.getIsCache()), menu.getPath()));
                children.setQuery(menu.getQuery());
                childrenList.add(children);
                router.setChildren(childrenList);
            } else if (menu.getParentId().intValue() == 0 && isInnerLink(menu)) {
                router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon()));
                router.setPath("/inner");
                List<RouterVo> childrenList = Lists.newArrayList();
                RouterVo children = new RouterVo();
                String routerPath = innerLinkReplaceEach(menu.getPath());
                children.setPath(routerPath);
                children.setComponent(BaseConstant.INNER_LINK);
                children.setName(CharSequenceUtil.upperFirst(routerPath));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getPath()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(SysMenu menu) {
        String component = BaseConstant.LAYOUT;
        if (CharSequenceUtil.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu)) {
            component = menu.getComponent();
        } else if (CharSequenceUtil.isEmpty(menu.getComponent()) && menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            component = BaseConstant.INNER_LINK;
        } else if (CharSequenceUtil.isEmpty(menu.getComponent()) && isParentView(menu)) {
            component = BaseConstant.PARENT_VIEW;
        }
        return component;
    }


    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isParentView(SysMenu menu) {
        return menu.getParentId().intValue() != 0 && BaseConstant.TYPE_DIR.equals(menu.getMenuType());
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(SysMenu menu) {
        String routerPath = menu.getPath();
        // 内链打开外网方式
        if (menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if (0 == menu.getParentId().intValue() && BaseConstant.TYPE_DIR.equals(menu.getMenuType())
                && BaseConstant.NO_FRAME.equals(menu.getIsFrame().toString())) {
            routerPath = "/" + menu.getPath();
        } else if (isMenuFrame(menu)) {
            // 非外链并且是一级目录（类型为菜单）
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 内链域名特殊字符替换
     *
     * @return 结果
     */
    public String innerLinkReplaceEach(String path) {
        path = CharSequenceUtil.replace(path, BaseConstant.HTTP, CharSequenceUtil.EMPTY);
        return CharSequenceUtil.replace(path, BaseConstant.HTTPS, CharSequenceUtil.EMPTY);
    }

    /**
     * 是否为内链组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isInnerLink(SysMenu menu) {
        return menu.getIsFrame().toString().equals(BaseConstant.NO_FRAME) && (HttpUtil.isHttp(menu.getPath()) || HttpUtil.isHttps(menu.getPath()));
    }

    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(SysMenu menu) {
        String routerName = CharSequenceUtil.upperFirst(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu)) {
            routerName = CharSequenceUtil.EMPTY;
        }
        return routerName;
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMenuFrame(SysMenu menu) {
        return menu.getParentId().intValue() == 0 && BaseConstant.TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame().toString().equals(BaseConstant.NO_FRAME);
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list     分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<SysMenu> getChildPerms(List<SysMenu> list, int parentId) {
        // 获取所有顶级菜单
        List<SysMenu> returnList = list.stream().filter(item -> item.getParentId() == parentId).collect(Collectors.toList());
        for (SysMenu parentMenu : returnList) {
            // 根据父级菜单递归将所有子级菜单填充
            recursionFn(list, parentMenu);
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list 菜单列表
     * @param t    父级菜单
     */
    private void recursionFn(List<SysMenu> list, SysMenu t) {
        // 得到子节点列表
        List<SysMenu> childList = list.stream().filter(item -> item.getParentId().intValue() == t.getMenuId().intValue()).collect(Collectors.toList());
        t.setChildren(childList);
        for (SysMenu child : childList) {
            if (hasChild(list, child)) {
                recursionFn(list, child);
            }
        }
    }

    /**
     * 判读是否有子级菜单
     *
     * @param list 列表
     * @param menu 菜单
     * @return 结果
     */
    private boolean hasChild(List<SysMenu> list, SysMenu menu) {
        List<SysMenu> childList = list.stream().filter(item -> item.getParentId().intValue() == menu.getMenuId().intValue()).collect(Collectors.toList());
        return childList.size() > 0;
    }

}
